package oot.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import oot.data.Config;
import oot.data.Connection;
import oot.data.JSonPaser;
import oot.data.Tweet;
import oot.data.User;
import oot.tab.activity.R;
import oot.utils.AtTokenizer;
import oot.utils.BitmapUtils;

import org.json.JSONException;
import org.json.JSONObject;

import ott.adapter.UserAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class TweetActivity extends Activity {
	public static final int GALLERY = 1;
	public static final int CAMERA = 2;
	private Context mContext;
	private Button btSendTweet;
	private Button btDismis;
	private TextView tvCharLeft;
	private JSONObject js;
	private ProgressDialog progressDialog;
	private MultiAutoCompleteTextView composeTweet;
	private ImageView imgCamera;
	private ImageView imgGallery;
	private ImageView imgTag;
	private ArrayList<User> listUsers;
	private UserAdapter adapter;
	private Tweet mTweet;
	private ImageView imgPicture;
	public static Uri mImageCaptureUri;
	private int imageWidth;
	private int imageHeight;
	private int useCode = 0;
	private CheckBox btnLocation;
	private TextView tvUserName;
	private TextView v;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// setContentView(R.layout.flash_screen_layout);
		mContext = this;
		imageWidth = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
						.getDisplayMetrics());
		imageHeight = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
						.getDisplayMetrics());

		getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
				WindowManager.LayoutParams.MATCH_PARENT);
		Tweet tempT = (Tweet) (getIntent()
				.getSerializableExtra(Config.TEMP_TWEET));
		mTweet = tempT;
		this.overridePendingTransition(R.anim.show, R.anim.hide);
		renderView();
	}
	private final TextWatcher mTextEditorWatcher = new TextWatcher() {
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// This sets a textview to the current length
			// super.onTextChanged(s,start,before,count);
			String textLeft = "" + (140 - s.length());
			tvCharLeft.setText(textLeft);
			if (Integer.parseInt(textLeft) <= 10)
				tvCharLeft.setTextColor(Color.RED);
			else {
				tvCharLeft.setTextColor(Color.WHITE);
			}
			// composeTweet.
		}

		public void afterTextChanged(Editable s) {
		}
	};

	public void onConfigurationChanged(
			android.content.res.Configuration newConfig) {
		Log.e("Config", "Config change");
	};

	public Tweet getmTweet() {
		return mTweet;
	}

	public void setmTweet(Tweet mTweet) {
		this.mTweet = mTweet;
	}

	private void renderView() {
		// set
		setContentView(R.layout.tweet_layout);
		progressDialog = new ProgressDialog(mContext);
		btSendTweet = (Button) findViewById(R.id.bt_dialog_tweet);
		tvCharLeft = (TextView) findViewById(R.id.tv_char_left);
		btDismis = (Button) findViewById(R.id.bt_dialog_cancel);
		composeTweet = (MultiAutoCompleteTextView) findViewById(R.id.auto_text_tweet);
		composeTweet.setText(mTweet.getContent());
		composeTweet.addTextChangedListener(mTextEditorWatcher);
		imgCamera = (ImageView) findViewById(R.id.img_tweet_camera);
		imgGallery = (ImageView) findViewById(R.id.img_tweet_gallery);
		imgTag = (ImageView) findViewById(R.id.img_tweet_at);
		imgPicture = (ImageView) findViewById(R.id.img_tweet_layout_preview);
		btnLocation = (CheckBox) findViewById(R.id.cb_place);
		tvUserName = (TextView) findViewById(R.id.tv_userid);
		v  = (TextView)findViewById(R.id.tv_indicator);
		tvUserName.setText(FlashScreenActivity.user.getUserName());
		createListUser();
		composeTweet.setThreshold(100);
		composeTweet.setDropDownHeight(LayoutParams.MATCH_PARENT);
		// composeTweet.setDropDownVerticalOffset(100);
		composeTweet.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				v.setText(s);
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
		composeTweet.setTokenizer(new AtTokenizer());
		if(mTweet.getContent()!=null)
			composeTweet.setSelection(mTweet.getContent().length());
		// composeTweet.getCo
		imgTag.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				composeTweet.append(" @");
				composeTweet.setThreshold(1);
				// composeTweet.SETC
			}
		});
		imgGallery.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				useCode = GALLERY;
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_PICK);
				// mContext.star
				((Activity) mContext).startActivityForResult(
						Intent.createChooser(intent, "Select Picture"), GALLERY);

			}
		});
		imgCamera.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Intent intent = new Intent(mContext,
				// DoShotCameraActivity.class);
				useCode = CAMERA;
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				mImageCaptureUri = makeFilename("tmp_avatar_");
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
						mImageCaptureUri);
				((Activity) mContext).startActivityForResult(intent, CAMERA);
			}
		});
		btDismis.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// dismiss();
				finish();
			}
		});
		btSendTweet.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String contentTweet = composeTweet.getText().toString();
				mTweet.setContent(contentTweet);
				mTweet.setImgURL("");
				doPostTweet(mTweet);
				finish();
				// progressDialog.show();
			}
		});

		btnLocation.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(),
						FBConnect.class);
				startActivity(intent);
			}
		});
		AQuery a = new AQuery(this);
		a.id(R.id.img_user_avata)
				.visible()
				.image(Connection.BASE_URL_IMAGE+FlashScreenActivity.user.getUserAvatarURL(), true, true,
						50, R.drawable.m05_item_avar);

	}

	private void doPostTweet(Tweet t) {
		String api = "Tweets/update";
		RequestParams params = new RequestParams();
		params.put("content", t.getContent());
		params.put("image_url", t.getImgURL());
		params.put("parent_id", t.getParentTweetId());
		params.put("type", t.getType());
		params.put("place_id", "222112212");
		params.put("user_id", FlashScreenActivity.user.getUserID());
		if (imgPicture.getVisibility() == View.VISIBLE)
			try {
				if (useCode == GALLERY) {
					params.put("media", new File(
							getRealPathFromURI(mImageCaptureUri)));
				} else {
					if (useCode == CAMERA) {
						params.put("media",
								new File(mImageCaptureUri.getPath()));
					}
				}
				api = "/tweets/update_with_media";
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		Log.i("test", params.toString());
		// Connection.setBaseURL("http://192.168.1.9");
		Log.i("api","--------"+api);
		Connection.post(api, params, new AsyncHttpResponseHandler() {
			public void onSuccess(String arg0) {
				Log.i("test", "return tweet --------" + arg0);
				if (progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
				super.onSuccess(arg0);
				try {
					js = new JSONObject(arg0);
					if (js.getInt("status_code") != 0) {
						// show error message if error occur

						Toast toast = Toast.makeText(mContext,
								js.getString("message"), Toast.LENGTH_SHORT);
						toast.show();
					} else {
						Toast toast = Toast.makeText(mContext,
								js.getString("message"), Toast.LENGTH_SHORT);
						toast.show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			@Override
			public void onFailure(Throwable arg0, String arg1) {
				// TODO Auto-generated method stub
				super.onFailure(arg0, arg1);
				Log.e("test",arg1 + "false-----");
			}
		});
	}

	private void createListUser() {
		listUsers = new ArrayList<User>();
		adapter = new UserAdapter(this, R.layout.user_row, listUsers);
		composeTweet.setAdapter(adapter);
		//getListFollow();
	}
	

	public void getListFollow() {
		RequestParams requestParams = new RequestParams();
		requestParams.put("get_userid", FlashScreenActivity.user.getUserID());
		requestParams.put("paging", "0");
		Connection.post("follows/followers", requestParams,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String res) {
						super.onSuccess(res);
						Log.d("RES", res);
						JSonPaser.listFollowers(res, listUsers);
						Log.i("test", "bb" + listUsers.size());
						// adapter.notifyDataSetChanged();
						// composeTweet.setAdapter(adapter);
					}

					@Override
					public void onFailure(Throwable arg0, String res) {
						super.onFailure(arg0, res);
					}
				});
		Connection.post("follows/followings", requestParams,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String res) {
						super.onSuccess(res);
						Log.d("RES", res);
						JSonPaser.listFollowings(res, listUsers);
						Log.i("test", "aaa" + listUsers.size());
						// adapter.notifyDataSetChanged();

					}

					@Override
					public void onFailure(Throwable arg0, String res) {
						super.onFailure(arg0, res);
					}
				});
	}

	public String getRealPathFromURI(Uri contentUri) {
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(contentUri, proj, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@SuppressLint({ "ParserError", "ParserError" })
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == GALLERY) {
				mImageCaptureUri = data.getData();
				imgPicture.setImageBitmap(BitmapUtils
						.decodeSampledBitmapFromFile(
								getRealPathFromURI(mImageCaptureUri),
								imageWidth, imageHeight));
				imgPicture.setVisibility(View.VISIBLE);
			}
			if (requestCode == CAMERA) {

				imgPicture.setImageBitmap(BitmapUtils
						.decodeSampledBitmapFromFile(
								mImageCaptureUri.getPath(), imageWidth,
								imageHeight));

				imgPicture.setVisibility(View.VISIBLE);
			}
		}
	}

	public Uri makeFilename(String prefix) {
		String direct = "/faketwitter";

		File directory = new File(Environment.getExternalStorageDirectory()
				+ direct);
		if (!directory.exists()) {
			boolean test = directory.mkdir();
			if (test) {
				Log.e("OK", "Tao ok");
			} else {
				Log.e("FAILE", "TAO FAILE");
			}
		}
		File file = new File(directory, prefix
				+ String.valueOf(System.currentTimeMillis()));
		return Uri.fromFile(file);
	}

}
